//
//  JXWCommonConst.swift
//  XWClassroom
//
//  Created by xianquan on 2023/11/20.
//

import UIKit
import TYUIKit
import NHHUDExtend
import AVFoundation

public enum AppEnvironment{
    case test
    case gray
    case product
    
    var oldBaseUrl: String{
        switch self {
        case .test:
            return "http://admin.jichacha.vip"
        case .gray:
            return "http://admin.jichacha.vip"
        case .product:
            return "http://admin.jichacha.vip"
        }
    }
    
    var newBaseUrl: String{
        switch self {
        case .test:
            return "http://admin.jichacha.vip"
        case .gray:
            return  "http://admin.jichacha.vip"
        case .product:
            return  "http://admin.jichacha.vip"
        }
    }
}

public let appEnvironment: AppEnvironment = .test

public let keyWindow = UIApplication.shared.windows.first { $0.isKeyWindow } ?? UIWindow()

public let isIpad = UIDevice.current.userInterfaceIdiom == .pad

public let wxAppId = "wx55816d76a14c6301"
public let wxAppSecret = "cdc3d7c57f389842c0cea1bcc28c2820"

public func isMac() -> Bool {
    if #available(iOS 14.0, *) {
        return ProcessInfo.processInfo.isiOSAppOnMac
    } else {
        return false
    }
}

public let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""

public let buildVersion = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? ""

public func XWLog<T>(value : T, file: String = #file, method: String = #function, line: Int = #line){
    let logValue = "\((file as NSString).lastPathComponent)[\(line)], \(method): \(value)"
    ZHHomeLog.log(forDebug: "\(logValue)")
}

let toastContentHeight = "高度".height(for: adapt(16).medium, width: 100) + adapt(23)

public func toast(message: String, error: NSError? = nil){
    if let hud = MBProgressHUD.showOnlyText(message) {
        hud.margin = adapt(11.5)
        hud.h_margin = adapt(17)
        hud.label.font = adapt(16).regular
        hud.bezelView.style = .solidColor
        hud.bezelView.color = .black
        hud.bezelView.layer.cornerRadius = toastContentHeight / 2
    }
}

public func showLoading(_ view: UIView? = nil, title: String? = nil){
    MBProgressHUD.showLoad(to: view, title: title)
}

public func hideLoading(_ view: UIView? = nil){
    MBProgressHUD.hide(for: view)
}


public func screenWidth() -> CGFloat {
    UIScreen.main.bounds.width
}

public func screenHeight() -> CGFloat {
    UIScreen.main.bounds.height
}

public func screenBounds() -> CGRect {
    UIScreen.main.bounds
}

public let screenScale = UIScreen.main.scale

public let videoPlayerLeftSpace = isIpad ? 0.0 : (max(screenWidth(), screenHeight()) - min(screenWidth(), screenHeight()) * 16 / 9) / 2.0


public func pushToSBVC(name: String) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let viewController = storyboard.instantiateViewController(withIdentifier: name)
    TY_TopViewController().navigationController?.pushViewController(viewController, animated: true)
}

public func adapt(_ x: CGFloat, coefficient: CGFloat = 0) -> CGFloat{
    coefficient == 0 ? TY_ScreenAdaptionLength(x) : (isIpad ? coefficient : 1) * adaptNoCoefficient(x)
}

public func adaptNoCoefficient(_ x: CGFloat) -> CGFloat{
    x * min(screenWidth(), screenHeight()) / 375
}

public func convertTime(second: Double) -> String{
    let time = Int(second)
    let str_hour = String(format: "%02d", time/3600)
    let str_minute = String(format: "%02d", time%3600/60)
    let str_second = String(format: "%02d", time%60)
    if second / 3600 >= 1 {
        return "\(str_hour):\(str_minute):\(str_second)"
    }
    return "\(str_minute):\(str_second)"
}

public func synchronized(_ lock: AnyObject, closure: () -> ()) {
    objc_sync_enter(lock)
    closure()
    objc_sync_exit(lock)
}

public func checkMicrophonePermission(success: @escaping ()->()) {
    let mediaType = AVMediaType.audio
    switch AVCaptureDevice.authorizationStatus(for: mediaType) {
    case .authorized:
        // 授权已授予，可以进行录音操作
        success()
    case .notDetermined:
        // 请求录音权限
        AVCaptureDevice.requestAccess(for: mediaType) { granted in
            if granted {
                // 授权成功
                DispatchQueue.main.async {
                    success()
                }
            } else {
                // 授权被拒绝
                XWLog(value: "录音权限被拒绝")
            }
        }
    case .restricted, .denied:
        // 授权被拒绝或受限制
//        TYAlertView.showCommonAlert(title: "录音权限受限", message: "请开启录音权限", buttonTitles: ["去开启"], cancelButtonTitle: "取消") { alert, index in
//            if index == 1 {
//                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, completionHandler: nil)
//            }
//        }
        break
    @unknown default:
        break
    }
}


private var isLoadingToPush = false
public func canLoadingToPush() -> Bool {
    if isLoadingToPush {
        return false
    }
    isLoadingToPush = true
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        isLoadingToPush = false
    }
    return true
}

public extension Notification.Name {
    static let netWorkChanged = Notification.Name("netWorkChanged")
}

public var isNetworkError: Bool {
    if XWClassRoomManager.shared.isNetworkError == true {
        toast(message: "网络走丢了，请先检查网络吧")
    }
    return XWClassRoomManager.shared.isNetworkError
}

public extension Notification.Name {
    static let downloadVideo = Notification.Name("downloadVideo")
    
    static let downloadProgress = Notification.Name("downloadProgress")
    
    static let downloadSuccess = Notification.Name("downloadSuccess")
    
    static let saveToAlbum = Notification.Name("saveToAlbum")
    
}

public var shouldSaveImageToAlbum = false

